package controllers

import (
	"bufio"
	"encoding/base64"
	"github.com/astaxie/beego"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"
)
/**
 * 公共控制器
 */
type BaseController struct {
	 beego.Controller
}


/**
 * 信息返回
 */
type Msg struct {
	Code int
	Msg string
	Data interface{}
}
/**
 * ajax json成功返回
 */
func (this *BaseController) Suc(data interface{})  {
	res := Msg{200,"操作成功",data}
	this.Data["json"] = res
	this.ServeJSON()
	this.StopRun()
}
/**
 * ajax json 错误返回
 */
func (this *BaseController) Err(code int,msg string,data interface{})  {
	res := Msg{code,msg,data}
	this.Data["json"] = res
	this.ServeJSON()
	this.StopRun()
}
/**
 * base64上传
 */
func (this *BaseController) Base64Upload(fileurl string) string {

	DataArr := strings.Split(fileurl, ",")
	//去除包装，获取到base64编码
	imgBase64 := DataArr[1]
	//base64转码
	imgs,err := base64.StdEncoding.DecodeString(imgBase64)
	if err != nil {
		this.Err(2001,"base64 decode error:",err)
	}

	timenow := time.Now().UnixNano()
	path := "upload/"+strconv.FormatInt(timenow, 10)+".jpg"
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		this.Err(2001,"create file error:",err)
	}
	w := bufio.NewWriter(file) //创建新的 Writer 对象
	_, err3 := w.WriteString(string(imgs))
	if err3 != nil {
		this.Err(2001,"create file error:",err)
	}

	w.Flush()
	defer file.Close()
	return "/"+path
}

//正则获取内容中的图片
func (this *BaseController) ContentImg(str string) string {
	var imgRE = regexp.MustCompile(`<img[^>]+\bsrc=["']([^"']+)["']`)
	imgs := imgRE.FindAllStringSubmatch(str, -1)
	out := make([]string, len(imgs))
	for i := range out {
		pic := this.Base64Upload(imgs[i][1])
		str = strings.Replace(str, imgs[i][1], pic, -1)

	}
    return str
}

